package com.bbm.communitysystem.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.bbm.communitysystem.core.oss.OSS;
import com.bbm.communitysystem.domain.News;
import com.bbm.communitysystem.domain.OssFile;
import com.bbm.communitysystem.domain.UserInfo;
import com.bbm.communitysystem.domain.bo.NewsBo;
import com.bbm.communitysystem.domain.dto.NewsDto;
import com.bbm.communitysystem.mapper.NewsMapper;
import com.bbm.communitysystem.service.INewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bbm
 * @since 2025-02-13
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements INewsService {

    private final UserInfoServiceImpl userInfoService;

    private final OSS oss;

    @Override
    public NewsDto createNews(NewsBo newsBo) {

        List<OssFile> ossFiles = oss.saveFile("news", newsBo.getUpdateBy(), newsBo.getNewsImg());

        if (ossFiles.isEmpty()) {
            return null;
        }

        News news = new News();


        news.setNewsImg(ossFiles.get(0).getClientUrl());
        news.setOssId(ossFiles.get(0).getId());

        news.setNewsTitle(newsBo.getNewsTitle());
        news.setNewsContent(newsBo.getNewsContent());
        news.setStatus(3);
        news.setUpdateBy(newsBo.getUpdateBy());
        news.setNewsTime("----");
        news.setNewsAuthor(userInfoService.lambdaQuery()
                .eq(UserInfo::getId, newsBo.getUpdateBy())
                .one().getUserNick());
        news.setUpdateTime(System.currentTimeMillis() + "");
        news.setServerPath(ossFiles.get(0).getServerPath());
        boolean save = this.save(news);

        if (!save) {
            return null;
        }

        return BeanUtil.copyProperties(news, NewsDto.class);
    }

    @Override
    public NewsDto putNewsImg(NewsBo newsBo) {

        News byId = getById(newsBo.getId());

        oss.deleteFile(byId.getServerPath());

        List<OssFile> ossFiles = oss.saveFile("news", newsBo.getUpdateBy(), newsBo.getNewsImg());

        if (ossFiles.isEmpty()) {
            return null;
        }

        byId.setNewsImg(ossFiles.get(0).getClientUrl());
        byId.setServerPath(ossFiles.get(0).getServerPath());
        byId.setOssId(ossFiles.get(0).getId());

        boolean b = updateById(byId);

        if (!b) {
            return null;
        }

        return new NewsDto();
    }

    @Override
    public NewsDto delNewsImg(NewsBo newsBo) {
        News byId = getById(newsBo.getId());

        if (byId != null) {
            oss.deleteFile(byId.getServerPath());
        }

        boolean b = removeById(newsBo.getId());

        if (!b) {
            return null;
        }

        return new NewsDto();
    }
}
